package cn.wolfcode.wms.controller;

import cn.wolfcode.wms.domain.SystemMenu;
import cn.wolfcode.wms.qo.SystemMenuQueryObject;
import cn.wolfcode.wms.service.IPermissionService;
import cn.wolfcode.wms.service.ISystemMenuService;
import cn.wolfcode.wms.util.RequiredPermission;
import cn.wolfcode.wms.vo.JSONResult;
import cn.wolfcode.wms.vo.SystemMenuVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/systemMenu")
public class SystemMenuController {

    @Autowired
    private ISystemMenuService systemMenuService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission("菜单列表")
    public String list(@ModelAttribute("qo") SystemMenuQueryObject qo, Map map) {
        if (qo.getParentId() != null) {

            map.put("parents", systemMenuService.getParents(qo.getParentId()));
        }
        map.put("pageResult", systemMenuService.query(qo));
        return "/systemMenu/list";
    }

    @RequestMapping("/input")
    @RequiredPermission("菜单编辑")
    public String input(Long id, Long parentId, Map map) {

        if (parentId != null) {
            SystemMenu menu = systemMenuService.getById(parentId);
            map.put("parentName", menu.getName());
            map.put("parentId", menu.getId());
        } else {
            map.put("parentName", "根目录");
        }

        map.put("permissions", permissionService.listAll());
        if (id != null) {
            map.put("systemMenu", systemMenuService.getById(id));
        }
        return "/systemMenu/input";
    }

    @RequestMapping("/saveOrUpdate")
    @RequiredPermission("更新或新增菜单")
    @ResponseBody
    public JSONResult saveOrUpdate(SystemMenu systemMenu) {
        try {
            systemMenuService.saveOrUpdate(systemMenu);
        } catch (Exception e) {
            e.printStackTrace();
            return JSONResult.mark(e.getMessage());
        }
        return JSONResult.success("操作成功！");
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiredPermission("删除菜单")
    public JSONResult delete(Long id) {
        try {
            systemMenuService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            // 出错时返回错误信息
            return JSONResult.mark(e.getMessage());
        }
        return JSONResult.success("删除成功！");
    }

    @RequestMapping("/loadMenuByParentSn")
    @ResponseBody
    public List<SystemMenuVO> loadMenuByParentSn(String parentSn) {

        return systemMenuService.loadMenuByParentSn(parentSn);
    }
}
